/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dao.ulti.HibernateUtil;
import exception.LoginException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import pojo.Account;

/**
 *
 * @author Nero
 */
public class AccountDAO extends AbstractDAO<Account, String> {

    @Override
    protected Class getPOJOClass() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public static List<Account> getAccountList() {
        Session session = HibernateUtil.getSessionFactory().openSession();
        String hql = "SELECT * FROM Account";
        Query query = session.createQuery(hql);
        List<Account> list = query.list();
        session.close();
        return list;
    }

    public static Account getAccount(int id) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        String hql = "FROM Account acc WHERE acc.id = :ID";
        Query query = session.createQuery(hql);
        query.setParameter("ID", id);
        Account result = (Account) query.list();
        session.close();
        return result;
    }

    public static Account logIn(String username, String password, boolean adminRequest) throws HibernateException, Exception {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        String hql = "FROM Account a WHERE a.username = :USERNAME AND a.isDelete = :IS_DELETE";
        Query query = session.createQuery(hql);
        query.setParameter("USERNAME", username);
        query.setParameter("IS_DELETE", false);
        if (!query.list().isEmpty()) {
            Account result = (Account) query.uniqueResult();
            if (result.getPassword().equals(password)) {
                if (adminRequest) {
                    if (result.isAccountType()) {
                        session.close();
                        return result;
                    } else {
                        session.close();
                        throw new Exception("NOT_ALLOW");
                    }
                }
                session.close();
                return result;
            } else {
                session.close();
                throw new Exception("WRONG_PASSWORD");
            }
        } else {
            session.close();
            throw new Exception("NOT_EXIST");
        }
    }
}
